/*
Copyright(c) 2023 NeatLogic Co., Ltd. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package neatlogic.module.change.api;

import neatlogic.framework.asynchronization.threadlocal.UserContext;
import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.change.dto.*;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.exception.file.FileNotFoundException;
import neatlogic.framework.exception.type.PermissionDeniedException;
import neatlogic.framework.file.dao.mapper.FileMapper;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.process.dto.ProcessTaskStepVo;
import neatlogic.framework.process.stephandler.core.IProcessStepHandlerUtil;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.framework.change.constvalue.ChangeAuditType;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.framework.change.exception.ChangeHandleHasNotStartedException;
import neatlogic.framework.change.exception.ChangeStepCommentNotFoundException;
import neatlogic.framework.change.exception.ChangeStepNotFoundException;
import neatlogic.module.change.service.ChangeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeStepCommentEditApi extends PrivateApiComponentBase {

    @Resource
    private ChangeMapper changeMapper;

    @Resource
    private ChangeService changeService;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private IProcessStepHandlerUtil IProcessStepHandlerUtil;

    @Override
    public String getToken() {
        return "change/step/comment/edit";
    }

    @Override
    public String getName() {
        return "编辑变更步骤回复";
    }

    @Override
    public String getConfig() {
        return null;
    }

    @Input({
            @Param(name = "id", type = ApiParamType.LONG, isRequired = true, desc = "回复id"),
            @Param(name = "content", type = ApiParamType.STRING, desc = "描述"),
            @Param(name = "fileIdList", type = ApiParamType.JSONARRAY, desc = "附件id列表"),
            @Param(name = "source", type = ApiParamType.STRING, defaultValue = "pc", desc = "来源")
    })
    @Description(desc = "编辑变更步骤回复")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long id = jsonObj.getLong("id");
        ChangeStepCommentVo commentVo = changeMapper.getChangeStepCommentById(id);
        if (commentVo == null) {
            throw new ChangeStepCommentNotFoundException(id);
        }
        ChangeStepVo changeStep = changeMapper.getChangeStepById(commentVo.getChangeStepId());
        if (changeStep == null) {
            throw new ChangeStepNotFoundException(commentVo.getChangeStepId());
        }
        if (changeService.isEditableComment(commentVo) == 0) {
            throw new PermissionDeniedException();
        }

        changeMapper.getChangeLockById(commentVo.getChangeId());
        ChangeStepCommentVo comment = new ChangeStepCommentVo();
        comment.setId(id);
        comment.setLcu(UserContext.get().getUserUuid());

        String content = jsonObj.getString("content");
        if (StringUtils.isNotBlank(content)) {
            ChangeContentVo contentVo = new ChangeContentVo(content);
            changeMapper.replaceChangeContent(contentVo);
            comment.setContentHash(contentVo.getHash());
        }

        if (StringUtils.isNotBlank(commentVo.getFileIdListHash())) {
            String fileIdListString = changeMapper.getChangeContentByHash(commentVo.getFileIdListHash());
            if (StringUtils.isNotBlank(fileIdListString)) {
                List<Long> fileIdList = JSON.parseArray(fileIdListString, Long.class);
                for (Long fileId : fileIdList) {
                    changeMapper.deleteChangeStepFileByFileId(fileId);
                }
            }
        }
        List<Long> fileIdList = JSON.parseArray(JSON.toJSONString(jsonObj.getJSONArray("fileIdList")), Long.class);
        if (CollectionUtils.isNotEmpty(fileIdList)) {
            for (Long fileId : fileIdList) {
                if (fileMapper.getFileById(fileId) == null) {
                    throw new FileNotFoundException(fileId);
                }
                changeMapper.insertChangeStepFile(new ChangeStepFileVo(commentVo.getChangeId(), commentVo.getChangeStepId(), fileId));
            }
            ChangeContentVo fileContent = new ChangeContentVo(JSON.toJSONString(fileIdList));
            changeMapper.replaceChangeContent(fileContent);
            comment.setFileIdListHash(fileContent.getHash());
        }
        changeMapper.updateChangeStepCommentById(comment);

        ProcessTaskStepChangeVo processTaskStepChangeVo = changeMapper.getProcessTaskStepChangeHandleByChangeId(commentVo.getChangeId());
        if (processTaskStepChangeVo == null) {
            throw new ChangeHandleHasNotStartedException();
        }

        ProcessTaskStepVo currentProcessTaskStepVo = new ProcessTaskStepVo();
        currentProcessTaskStepVo.setProcessTaskId(processTaskStepChangeVo.getProcessTaskId());
        currentProcessTaskStepVo.setId(processTaskStepChangeVo.getProcessTaskStepId());
        currentProcessTaskStepVo.getParamObj().put("changeStepName", changeStep.getName());
        currentProcessTaskStepVo.getParamObj().put("source", jsonObj.getString("source"));
        IProcessStepHandlerUtil.audit(currentProcessTaskStepVo, ChangeAuditType.EDITCOMMENTCHANGESTEP);
        return null;
    }

}
